﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kugar.Core.BaseStruct;
using Kugar.Core.Data.MSSQLHelper;
using Kugar.Core.Security;
using Kugar.ERPFramework.BLLInterface;
using Kugar.Core.ExtMethod;
using System.Data.SqlClient;
using System.Data;
using System.Net;
using Kugar.ERPFramework.Entity;
using Kugar.Core.BaseStruct;
using Kugar.Core.Configuration;
using Kugar.ERPFramework.ServiceCommon;
using IPermissionManager = Kugar.Core.Security.IPermissionProvider;


namespace Kugar.ERPFramework.ServiceSystemBLL
{
    public class SystemModule : BaseModule, ISystemModule
    {
        private CustomConfigManager _configManager=new CustomConfigManager();

        public SystemModule(IProjectInstance instance):base(instance)
        {
        }

        public ResultReturn<string[]> GetUserNameList()
        {
            
            using (var reader = CurrentConnection.ExecuteReader("select username from sys_Users where Status=0"))
            {
                var lst = new List<string>();

                reader.Foreach(x => lst.Add(reader.GetValue(0).ToStringEx()));

                return new ResultReturn<string[]>(true) { ReturnData = lst.IgnoreSpecial(x=>string.IsNullOrWhiteSpace(x)).ToArray() };

            }
            
        }

        public ResultReturn BackupDatabase(string backupPath)
        {
            using (var conn=GetConnection())
            {
                try
                {
                    conn.Backup(DBBackupType.DB, backupPath, conn.Connection.Database);
                    return new ResultReturn(true);
                }
                catch (Exception ex)
                {
                    return new ResultReturn(false,error:ex);
                }
                
            }
        }

        public ResultReturn<int> Login(string userName, string pw,IPAddress address)
        {
            userName = userName.Trim();
            pw = pw.Trim();

            if (userName.IsNullOrEmpty())
            {
                return new ResultReturn<int>(false,message:"用户名不能为空");
            }

            if (pw.IsNullOrEmpty())
            {
                pw = "";
            }

            pw = pw.MD5_32().MD5_32();

            var cmd = base.CurrentConnection.CreateCommand();
            cmd.CommandText = "select top 1 userid from sys_Users where username=@userName and password=@pw";
            cmd.CommandType = CommandType.TableDirect;
            cmd.AddParameter("@userName",DbType.String ,userName);
            cmd.AddParameter("@pw",DbType.String, pw);

            try
            {
                var userID = base.CurrentConnection.ExecuteScalar<int>(cmd);

                if (userID>0)
                {
                    base.CurrentConnection.ExecuteNoQuery("update sys_Users set LastLoginDt=getdate(),LastLoginIP=" + address.Address);

                    ProjectInstance.Session.UserID = userID;

                    base.ProjectInstance.Session["CurrentUserID"] = userID;

                    return new ResultReturn<int>(true) { ReturnData = userID };
                }
                else
                {
                    return new ResultReturn<int>(false, message: "登录失败,不存在指定用户名或指定密码错误");
                }
            }
            catch (Exception ex)
            {
                return new ResultReturn<int>(false, error: ex);
            }
            
        }

        public ResultReturn Logout()
        {

            ProjectInstance.Session.UserID = -1;

            ProjectInstance.Session["CurrentUserID"] = -1;

            return  new SuccessResuleReturn();
        }

        public ResultReturn<LoginUserInfo> GetUserInfoByID(int userID)
        {
            //TODO:返回用户信息

            var info = getUserInfoByIDInternal(userID);

            if (info != null)
            {
                return new Core.BaseStruct.ResultReturn<LoginUserInfo>(true, info);
            }
            else
            {
                return new ResultReturn<LoginUserInfo>(false, message: "不存在指定ID的用户");
            }
            
        }

        private LoginUserInfo getUserInfoByIDInternal(int userID)
        {
            var conn = CurrentConnection;

            var lst = conn.ExecuteDataEntity<LoginUserInfo>(string.Format("select * from sys_Users where userID={0}", userID),null,null);

            if (lst != null)
            {
                return lst.FirstOrDefault();
            }
            else
            {
                return null;
            }

        }

        public ResultReturn<string> GetSerialNumber(string moduleID)
        {
            
        }

        public ResultReturn<ICustomConfigSection> GetConfigBySectionName(string sectionName)
        {
            var config = _configManager[sectionName];

            if (config==null)
            {
                return new ResultReturn<ICustomConfigSection>(true, config);
            }
            else
            {
                return new ResultReturn<ICustomConfigSection>(false);
            }
        }

        public ResultReturn GetPermissionListByUserID(int userid)
        {
            
        }

        public ResultReturn UpdateConfig(string sectionName, KeyValuePair<int,string>[] configs )
        {
            var conn = GetConnection();

            using (conn)
            {
                conn.BeginTransaction();

                try
                {
                    using (var cmd=conn.CreateCommand())
                    {
                        cmd.Transaction = conn.CurrentTransaction;
                        cmd.CommandText = "update sys_configs set value=@value where ID=@id";
                        cmd.AddParameter("@value",DbType.String, "");
                        cmd.AddParameter("@id",DbType.Int32, 0);

                        foreach (var  config in configs)
                        {
                            cmd.Parameters["@value"].Value = config.Value;
                            cmd.Parameters["@id"].Value = config.Key;

                            cmd.ExecuteNonQuery();
                        }
                    }

                    conn.CommitTransaction();

                    return new SuccessResuleReturn();
                }
                catch (Exception ex)
                {
                    conn.RollbackTransaction();   
                    return new ResultReturn(false,error:ex);
                }
            }
        }

        public int CurrentUserID
        {
            get { return ProjectInstance.Session.UserID; }

        }

        #region ISystemModule 成员


        public ResultReturn<LoginUserInfo[]> GetOnlineUser()
        {
            var sessionManager = CustomSession.Default;

            var lst=new List<LoginUserInfo>();

            foreach (var sessionItem in sessionManager)
            {
                if (sessionItem.UserID>0)
                {
                    lst.Add(getUserInfoByIDInternal(sessionItem.UserID));
                }
            }

            return new ResultReturn<LoginUserInfo[]>(true, returnData: lst.ToArray());
        }

        public ResultReturn SetUserOffline(int userID)
        {
            var sessionManager = CustomSession.Default;

            var sessionID = "";

            foreach (var sessionItem in sessionManager)
            {
                if (sessionItem.UserID == userID)
                {
                    sessionID = sessionItem.SessionID;
                    sessionItem.UserID = -1;
                }
            }

            sessionManager.Remvoe(sessionID);
        }

        public ResultReturn SetAllUserOffline()
        {
            var sessionManager = CustomSession.Default;

            sessionManager.Clear();

            return new SuccessResuleReturn();
        }

        public ResultReturn<object> GetCurrentPermission()
        {
            throw new NotImplementedException();
        }

        public ResultReturn<ILoginUserManager> GetUserManager()
        {
            throw new NotImplementedException();
        }

        public ResultReturn SendMessageToAllUser(string message)
        {
            var conn = CurrentConnection;

            using (var cmd=conn.CreateCommand())
            {
                cmd.CommandType= CommandType.StoredProcedure;
                cmd.CommandText = "exec @re= Sys_MessageManager_NewMessageToAllUser @messageContent,@createUserID";
                cmd.AddParameter("@messageContent",DbType.String, message);
                cmd.AddParameter("@createUserID",DbType.Int32,CurrentUserID);

                var par=cmd.CreateParameter();

                par.ParameterName = "@re";
                par.DbType=DbType.Int32;
                par.Direction= ParameterDirection.InputOutput;
                par.Value = 0;

                cmd.Parameters.Add(par);

                try
                {
                    cmd.ExecuteNonQuery();

                    if (((int)par.Value)>0)
                    {
                        return new SuccessResuleReturn(par.Value);
                    }
                    else
                    {
                        return new FailResultReturn("添加消息失败");
                    }
                }
                catch (Exception ex)
                {
                    return new FailResultReturn(ex);
                }
            }
        }

        public ResultReturn SendMessageToUsers(int userID, string message,int[] revUserIDList)
        {
            if (userID<0 && userID!=-2)
            {
                return new FailResultReturn("创建者ID不允许为空");
            }

            if (string.IsNullOrWhiteSpace(message))
            {
                return new FailResultReturn("消息内容不能为空");
            }

            if (revUserIDList==null || revUserIDList.Length<=0)
            {
                return  new FailResultReturn("请选择接收者");
            }

            var conn = CurrentConnection;

            using (var cmd = conn.CreateCommand())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "exec @re= Sys_MessageManager_NewMessageToUsers @messageContent,@createUserID,@revUserIDList";
                cmd.AddParameter("@messageContent", DbType.String, message);
                cmd.AddParameter("@createUserID", DbType.Int32, CurrentUserID);
                cmd.AddParameter("@revUserIDList", DbType.String, revUserIDList.JoinToString(','));
                var par = cmd.CreateParameter();

                par.ParameterName = "@re";
                par.DbType = DbType.Int32;
                par.Direction = ParameterDirection.InputOutput;
                par.Value = 0;

                cmd.Parameters.Add(par);

                try
                {
                    cmd.ExecuteNonQuery();

                    if (((int)par.Value) > 0)
                    {
                        return new SuccessResuleReturn(par.Value);
                    }
                    else
                    {
                        return new FailResultReturn("添加消息失败");
                    }
                }
                catch (Exception ex)
                {
                    return new FailResultReturn(ex);
                }
            }
        }

        #endregion
    }

    public class LoginUserManager:ILoginUserManager
    {
        private IPermissionManager _permissionManager = null;
        private SystemModule _systemModule = null;
        
        public LoginUserManager(IProjectInstance instance)
        {
            
        }

        public ResultReturn<LoginUserInfo[]> GetAllUser()
        {
            
        }

        public ResultReturn<LoginUserInfo> GetUserInfoByUserID(int userID)
        {
            throw new NotImplementedException();
        }

        public ResultReturn<int> CreateUser(string userName, string password)
        {
            throw new NotImplementedException();
        }

        public ResultReturn DeleteUser(string userName)
        {
            throw new NotImplementedException();
        }

        public ResultReturn StopUser(string userName)
        {
            throw new NotImplementedException();
        }

        public ResultReturn<LoginUserInfo[]> SearchUserByName(string userName)
        {
            throw new NotImplementedException();
        }

        public ResultReturn<RMS_PermissionValueCollection> GetCurrentUserPermission()
        {
            return new ResultReturn < RMS_PermissionValueCollection >(true, returnData: _permissionManager.GetUserPermissionProvider(_systemModule.CurrentUserID).GetPermissionListByUserID());
        }

        public IProjectInstance ProjectInstance { get; private set; }
    }
}
